package org.song.util;


import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FunctionUtil {

    public static String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
            "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
            "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"};

    public static String generateId(int length) {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        int step = 8;
        int offset = 4;
        switch (length) {
            case 8:
                step = 8;
                offset = 4;
                break;
            case 16:
                step = 16;
                offset = 2;
                break;
        }
        for (int i = 0; i < step; i++) {
            String str = uuid.substring(i * offset, i * offset + offset);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 62]);
        }
        return shortBuffer.toString().toLowerCase();
    }

    public static String getRandomString(int length) {
        String source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(source.charAt(number));
        }
        return sb.toString();
    }

    public static String getRandomNum(int length) {
        String source = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(10);
            sb.append(source.charAt(number));
        }
        return sb.toString();
    }

    public static boolean checkStr(String str) {
        if (!StringUtils.isEmpty(str)) {
            return true;
        }
        return false;
    }

    public static String md5(String input) throws NoSuchAlgorithmException {
        String result = input;
        if (input != null) {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());
            BigInteger hash = new BigInteger(1, md.digest());
            result = hash.toString(16);
            if (result.length() % 2 != 0) {
                result = "0" + result;
            }
        }
        return result;
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {

            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            }
            return ip;
        }

        ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }

        return request.getRemoteAddr();
    }

    public static String getPassword(String password, String salt) {
        String pwd = "";
        try {
            pwd = md5(password + salt);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return pwd;
    }

    public static boolean checkMobile(String mobile) {
        boolean flag = false;
        try {
            Pattern regx = Pattern.compile("^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[35678]|18[0-9]|19[89])\\d{8}$");
            Matcher matcher = regx.matcher(mobile);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public static boolean checkPic(MultipartFile picture) {
        String fileName = picture.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            return false;
        }
        String fileType = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        if (!fileType.matches("^.*(jpg|png|gif|jpeg|svg)$")) {
            return false;
        }
        return true;
    }

    public static String getWeeksHash() {
        Calendar c = Calendar.getInstance();
        int year = c.get(1);
        int month = c.get(2) + 1;
        int weeks = c.get(4);
        return year + "/" + month + "/" + weeks;
    }

    public static boolean checkVideo(MultipartFile picture) {
        String fileName = picture.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            return false;
        }

        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (!fileType.matches("^.*(mp4|MP4)$")) {
            return false;
        }

        return true;
    }

    public static String getRedisKey(String prefix, Object key) {
        return prefix + key;
    }
}
